<?php

if (!defined('__COLA_DIR__')) exit;

/**
 * 内容的文章基类
 *
 * @author edikud
 * @package Widget
 * @copyright Copyright (c) 2019 Cola (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */

class Widget_Archive extends Widget_Abstract_Contents
{
    /**
     * 调用的风格文件
     *
     * @access protected
     * @var string
     */
    protected $_themeFile;
    
    /**
     * 风格目录
     * 
     * @access protected
     * @var string
     */
    protected $_themeDir;

    /**
     * 本页关键字
     *
     * @access protected
     * @var string
     */
    protected $_keywords;

    /**
     * 本页描述
     *
     * @access protected
     * @var string
     */
    protected $_description;

    /**
     * 本页标题
     *
     * @access protected
     * @var string
     */
    protected $_title = NULL;
    
    /**
     * 类型
     *
     * @access protected
     * @var string
     */
    protected $_type = 'index';
	
    /**
     * 别名
     *
     * @access protected
     * @var string
     */
    protected $_alias;	
	
    /**
     * 内容个数
     *
     * @access protected
     * @var integer
     */
    protected $_total = false;

    /**
     * 当前页
     *
     * @access protected
     * @var integer
     */
    protected $_currentPage = 1;

    /**
     * 生成分页的内容
     *
     * @access protected
     * @var array
     */
    protected $_pageRow = array();

    /**
     * 设置分页对象
     *
     * @access protected
     * @var Page
     */
    protected $_pageNav;
	
    /**
     * 标记是否为从外部调用
     *
     * @access private
     * @var boolean
     */
    private $_outside = false;
	
    /**
     * 是否为单一归档
     *
     * @access private
     * @var string
     */
    private $_single = false;
	
    /**
     * handle
     *
     * @access protected
     * @var array
     */
    protected $_handle = array(
            'index'                     =>  'indexHandle',
            'index_page'                =>  'indexHandle',
            404                         =>  'error404Handle',
            'page'                      =>  'singleHandle',
            'post'                      =>  'singleHandle',
            'attachment'                =>  'singleHandle',
            'comment_page'              =>  'singleHandle',
            'category'                  =>  'categoryHandle',
            'category_page'             =>  'categoryHandle',
            'tag'                       =>  'tagHandle',
            'tag_page'                  =>  'tagHandle',
            'author'                    =>  'authorHandle',
            'author_page'               =>  'authorHandle',
            'search'                    =>  'searchHandle',
            'search_page'               =>  'searchHandle',
			'ucenter'                   =>  'ucenterHandle',
			'logout'                    =>  'logoutHandle',
            'login'                     =>  'loginHandle',
            'register'                  =>  'registerHandle',
        );
	
    /**
     * layout
     *
     * @access protected
     * @var array
     */
    protected $_layout = array(
            'index'                     =>  array('Widget_Ucenter_Home', 'indexList'),
            'user-profile'              =>  array('Widget_Users_Profile', 'form'),
            'user-password'             =>  array('Widget_Users_Profile', 'passwordForm'),
			'comments'                  =>  array('Widget_Comments_Ucenter', 'commentList'),
            'plugins'                   =>  array('Widget_Plugins_Ucenter', 'pluginsList'),
            'themes'                    =>  array('Widget_Themes_Ucenter', 'themesList'),			
			'theme'                     =>  array('Widget_Themes_Ucenter', 'themesEditor'),
            'tags'                      =>  array('Widget_Metas_Tag_Ucenter', 'tagList'),
            'tag'                       =>  array('Widget_Metas_Tag_Edit', 'form'),
            'categories'                =>  array('Widget_Metas_Category_Ucenter', 'categoryList'),
            'category'                  =>  array('Widget_Metas_Category_Edit', 'form'),
			'posts'                     =>  array('Widget_Contents_Post_Ucenter', 'postList'),
            'post'                      =>  array('Widget_Contents_Post_Edit', 'form'),
			'pages'                     =>  array('Widget_Contents_Page_Ucenter', 'pageList'),
            'page'                      =>  array('Widget_Contents_Page_Edit', 'form'),
			'users'                     =>  array('Widget_Users_Ucenter', 'userList'),
            'user'                      =>  array('Widget_Users_Edit', 'form'),
            'options-general'           =>  array('Widget_Options_General', 'form'),
			'options-discussion'        =>  array('Widget_Options_Discussion', 'form'),
			'options-comments'          =>  array('Widget_Options_General', 'form'),
			'options-reading'           =>  array('Widget_Options_Reading', 'form'),
			'options-permalink'         =>  array('Widget_Options_Permalink', 'form'),
			'options-theme'             =>  array('Widget_Themes_Config', 'form'),			
			'options-plugin'            =>  array('Widget_Plugins_Config', 'form'),
			'login'                     =>  array('Widget_Users_Login', 'form'),
			'register'                  =>  array('Widget_Users_Register', 'form'),
        );

	
    /**
     * 构造函数,初始化组件
     *
     * @param mixed $request
     * @param mixed $response
     * @param mixed $params
     * @throws Widget_Exception
     */
    public function __construct($request, $response, $params = NULL)
    {
        parent::__construct($request, $response, $params);

        $this->parameter->setDefault(array(
			'alias'             =>  '',
            'pageSize'          =>  $this->options->pageSize,
        ));
		
        /** 初始化皮肤路径 */
        $this->_themeDir = $this->options->themeDir;
		
        /** 用于判断是路由调用还是外部调用 */
        if (NULL == $this->parameter->type) {
            $this->parameter->type = Router::$current;
        } else {
            $this->_outside = true;
        }

		/** 插件接口 */
		//HOOK PLUG_Archive($this);
    }

    /**
     * 判断参数是否满足要求
     *
     * @access public
     * @param mixed $query 条件
     * @return boolean
     */
    public function is($type, $alias = NULL)
    {
        return ($type == $this->_type ||
        (($this->_single ? 'single' : 'archive') == $type && 'index' != $this->_type))
        && (empty($alias) ? true : $alias == $this->_alias);
    }

    /**
     * @param $title the $_title to set
     */
    public function setTitle($title)
    {
        $this->_title = $title;
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->_title;
    }
	
    /**
     * 增加标题
     * @param string $title 标题
     * @return void
     */
    public function addTitle($title)
    {
        $current = $this->getTitle();
        $current[] = $title;
        $this->setTitle($current);
    }

    /**
     * @param $layout the $_layout to set
     */
    public function setLayout($name, $value)
    {
		if(empty($value)){
			unset($this->_layout[$name]);
		}else{
			$this->_layout[$name] = $value;
		}
    }

    /**
     * @return array
     */
    public function getLayout()
    {
        return $this->_layout;
    }
	
    /**
     * @param $handle the $_handle to set
     */
    public function setHandle($name, $value)
    {
		if(empty($value)){
			unset($this->_handle[$name]);
		}else{
			$this->_handle[$name] = $value;
		}
    }

    /**
     * @return array
     */
    public function getHandle()
    {
        return $this->_handle;
    }
	
    /**
     * @param $description the $_description to set
     */
    public function setDescription($description)
    {
        $this->_description = $description;
    }

    /**
     * @return string
     */
    public function getDescription()
    {
        return $this->_description;
    }
	
    /**
     * @param $keywords the $_keywords to set
     */
    public function setKeywords($keywords)
    {
        $this->_keywords = $keywords;
    }

    /**
     * @return string
     */
    public function getKeywords()
    {
        return $this->_keywords;
    }

    /**
     * @param $alias the $_alias to set
     */
    public function setAlias($alias)
    {
        $this->_alias = $alias;
    }
	
    /**
     * @return string
     */
    public function getAlias()
    {
        return $this->_alias;
    }
	
    /**
     * @param $type the $_type to set
     */
    public function setType($type)
    {
        $this->_type = $type;
    }
	
    /**
     * @return string
     */
    public function getType()
    {
        return $this->_type;
    }	
	
    /**
     * @param $single the $_single to set
     */
    public function setSingle($single)
    {
        $this->_single = $single;
    }
	
    /**
     * @return string
     */
    public function getSingle()
    {
        return $this->_single;
    }
	
    /**
     * @param $themeFile the $_themeFile to set
     */
    public function setThemeFile($themeFile)
    {
        $this->_themeFile = $themeFile;
    }
    
    /**
     * @return string
     */
    public function getThemeFile()
    {
        return $this->_themeFile;
    }
	
    /**
     * @param $themeDir the $_themeDir to set
     */
    public function setThemeDir($themeDir)
    {
        $this->_themeDir = $themeDir;
    }
	
    /**
     * @return string
     */
    public function getThemeDir()
    {
        return $this->_themeDir;
    }
	
    /**
     * 输出标题
     * 
     * @param mixed $defines 
     * @param string $before 
     * @param string $end 
     * @access public
     * @return void
     */
    public function siteTitle($defines = NULL, $before = ' &raquo; ', $end = '')
    {
        if ($this->_title) {
            $define = '%s';
            if (is_array($defines) && !empty($defines[$this->parameter->type])) {
                $define = $defines[$this->parameter->type];
            }

            echo $before . sprintf($define, $this->_title) . $end;
        }
    }

    /**
     * 输出关键字
     *
     * @access public
     */
    public function siteKeywords($split = ',', $default = '')
    {
        echo empty($this->_keywords) ? $default : str_replace(',', $split, htmlspecialchars($this->_keywords));
    }


    /**
     * @return the $_description
     */
    public function siteDescription($default = '')
    {
        echo empty($this->_description) ? $default : htmlspecialchars($this->_description);
    }
	
    /**
     * @param $total the $_total to set
     */
    public function setTotal($total)
    {
        $this->_total = $total;
    }

    /**
     * @return int
     */
    public function getTotal()
    {
        return $this->_total;
    }

    public function setCurrentPage($currentPage)
    {
        $this->_currentPage = $currentPage;
    }
	
    /**
     * @return int
     */
    public function getCurrentPage()
    {
        return $this->_currentPage;
    }

    /**
     * 获取页数
     * 
     * @return integer
     */
    public function getTotalPage()
    {
        return ceil($this->_total / $this->parameter->pageSize);
    }
	
    /**
     * 设置分页对象
     * @param array $pageRow
     * @return void
     */
    public function setPageRow($pageRow)
    {
        $this->_pageRow = $pageRow;
    }

    /**
     * 获取分页对象
     * @return array
     */
    public function getPageRow()
    {
        return $this->_pageRow;
    }	
	
    /**
     * 评论地址
     * 
     * @access protected
     * @return string
     */
    protected function ___commentUrl()
    {
        /** 生成反馈地址 */
        /** 评论 */
        $commentUrl = parent::___commentUrl();
        
        //不依赖js的父级评论
        $reply = $this->request->filter('int')->replyTo;
        if ($reply && $this->is('single')) {
            $commentUrl .= '?parent=' . $reply;
        }
        
        return $commentUrl;
    }

    /**
     * 导入对象
     *
     * @access private
     * @param Widget_Archive $widget 需要导入的对象
     * @return void
     */
    private function import(Widget_Archive $widget)
    {
        $currentProperties = get_object_vars($this);
        foreach ($currentProperties as $name => $value) 
		{
            if (false !== strpos('|request|response|parameter|', '|' . $name . '|')) {
                continue;
            }

            if (isset($widget->{$name})) {
                $this->{$name} = $widget->{$name};
            } else {
                $method = ucfirst(trim($name, '_'));
                $setMethod = 'set' . $method;
                $getMethod = 'get' . $method;

                if (method_exists($this, $setMethod)
                    && method_exists($widget, $getMethod)) {
                    $this->{$setMethod}($widget->{$getMethod}());
                }
            }
        }
    }
	
    /**
     * 处理index
     *
     * @return void
     */
    public function indexHandle()
    {
        /** 设置类型 */
        $this->_type = 'index';
		
		/** 匹配类型 */
        $select = $this->select()
		    ->where('table.contents.type = ?', 'post');
		
		/** 计算数目 */
		$this->_total = (clone $select)
            ->select(array('COUNT(*)' => 'num'))
            ->fetchObject()
			->num;
		
        $select->page($this->_currentPage, $this->parameter->pageSize)
		    ->order('table.contents.cid', 'DESC');
		
		$this->query($select);
    }

    /**
     * 独立页处理
     *
     * @return void
     * @throws Widget_Exception
     */
    public function singleHandle()
    {
        if ('comment_page' == $this->parameter->type) {
            $matched = Router::match($this->request->permalink);

            if ($matched && $matched instanceof Widget_Archive && $matched->is('single')) {
                $this->import($matched);
                return;
            }
        }
		
		/** 设置单一类型 */
        $this->_single = true;
		
        /** 初始化类型 */
        $this->_type = 'single';

		$select = $this->select();
		
		/** 匹配类型 */
        if ('single' != $this->parameter->type) {
            $select->where('table.contents.type = ?', $this->parameter->type);
        }		
		
        /** 如果是单篇文章或独立页面 */
        if (isset($this->request->cid)) {
            $select->where('table.contents.cid = ?', $this->request->filter('int')->cid);
        }

        /** 匹配缩略名 */
        if (isset($this->request->alias)) {
            $select->where('table.contents.alias = ?', $this->request->alias);
        }
		
        $select->limit(1);
		$this->query($select);

        if (!$this->have() 
            || (isset($this->request->category) && $this->category != $this->request->category )
            || (isset($this->request->directory) && $this->request->directory != implode('/', $this->directory))) {
				
            if (!$this->_outside) {
                /** 对没有索引情况下的判断 */
                throw new Widget_Exception(_t('请求的地址不存在'), 404);
            } else {
                return;
            }
        }
		
        /** 设置模板 */
        if ($this->template) {
            /** 应用自定义模板 */
            $this->_themeFile = $this->template;
        }
		
        /** 设置类型 */
        list($this->_type) = explode('_', $this->type);
		
        /** 设置缩略名 */
        $this->_alias = ('post' == $this->_type) ? $this->cid : $this->alias;
    }

    /**
     * 处理分类
     *
     * @return void
     * @throws Widget_Exception
     */
    public function categoryHandle()
    {
        $categorySelect = $this->db
            ->select()
			->from('table.metas')
            ->where('type = ?', 'category')
            ->limit(1);

        if (isset($this->request->mid)) {
            $categorySelect->where('mid = ?', $this->request->filter('int')->mid);
        }

        if (isset($this->request->alias)) {
            $categorySelect->where('alias = ?', $this->request->alias);
        }

        if (isset($this->request->directory)) {
            $directory = explode('/', $this->request->directory);
            $categorySelect->where('alias = ?', $directory[count($directory) - 1]);
        }
		
        $category = $categorySelect->fetchRow();
		$category && $category = $this->widget('Widget_Metas_Category_List')
		    ->getCategory($category['mid']);
		
        if (empty($category)) {
            throw new Widget_Exception(_t('分类不存在'), 404);
        }

        if (isset($directory) && $category && ($this->request->directory != implode('/', $category['directory']))) {
            throw new Widget_Exception(_t('父级分类不存在'), 404);
        }

		/** 设置参数 */
		$this->request->setParam('mid', $category['mid']);

        /** 计算数目 */
		$this->_total = $category['contentsNum'];

		$cids = $this->db->select('table.relate.cid')
		    ->from('table.relate')
		    ->where('table.relate.mid = ?', $category['mid'])
		    ->page($this->_currentPage, $this->parameter->pageSize)
		    ->fetchAll();

		if($cids){
            $select = $this->select()
			    ->where('table.contents.cid IN ('.implode(',', array_column($cids, 'cid')).')')
			    ->order('table.contents.cid', 'DESC');
			$this->query($select);
		}

        /** 设置分页 */
        $this->_pageRow = array_merge($category, array(
            'alias'         =>  urlencode($category['alias']),
            'directory'     =>  implode('/', array_map('urlencode', $category['directory']))
        ));

        /** 设置关键词 */
        $this->_keywords = $category['name'];

        /** 设置描述 */
        $this->_description = $category['description'];

        /** 设置标题 */
        $this->_title = $category['name'];

        /** 设置类型 */
        $this->_type = 'category';
		
		/** 设置参数 */
		$this->_alias = $category['alias'];
    }

    /**
     * 处理标签
     *
     * @return void
     * @throws Widget_Exception
     */
    public function tagHandle()
    {
        $tagSelect = $this->db->select()
		    ->from('table.metas')
            ->where('type = ?', 'tag')
			->limit(1);

        if (isset($this->request->mid)) {
            $tagSelect->where('mid = ?', $this->request->filter('int')->mid);
        }

        if (isset($this->request->alias)) {
            $tagSelect->where('alias = ?', $this->request->alias);
        }
        $tag = $tagSelect->fetchRow(array($this->widget('Widget_Abstract_Metas'), 'filter'));
        if (empty($tag)) {
            throw new Widget_Exception(_t('标签不存在'), 404);
        }

		/** 设置参数 */
		$this->request->setParam('mid', $tag['mid']);

        /** 计算数目 */
		$this->_total = $tag['contentsNum'];

		$cids = $this->db->select('table.relate.cid')
		    ->from('table.relate')
		    ->where('table.relate.mid = ?', $tag['mid'])
		    ->page($this->_currentPage, $this->parameter->pageSize)
		    ->fetchAll();

		if($cids){
            $select = $this->select()
			    ->where('table.contents.cid IN ('.implode(',', array_column($cids, 'cid')).')')
			    ->order('table.contents.cid', 'DESC');
			$this->query($select);
		}

        /** 设置分页 */
        $this->_pageRow = array_merge($tag, array(
            'alias'  =>  urlencode($tag['alias'])
        ));

        /** 设置关键词 */
        $this->_keywords = $tag['name'];

        /** 设置描述 */
        $this->_description = $tag['description'];

        /** 设置标题 */
        $this->_title = $tag['name'];

        /** 设置类型 */
        $this->_type = 'tag';
		
		/** 设置参数 */
		$this->_alias = $tag['alias'];
    }

    /**
     * 处理作者
     *
     * @return void
     * @throws Widget_Exception
     */
    public function authorHandle()
    {
        $userSelect = $this->db
            ->select()
		    ->from('table.users')
            ->limit(1);

        if (isset($this->request->uid)) {
            $userSelect->where('uid = ?', $this->request->filter('int')->uid);
        }

        $user = $userSelect->fetchRow();
        if (empty($user)) {
            throw new Widget_Exception(_t('作者不存在'), 404);
        }

		/** 设置参数 */
		$this->request->setParam('uid', $user['uid']);
		
        /** 计算数目 */
		$this->_total = $user['contentsNum'];
		
        $select = $this->select()
		    ->where('table.contents.type = ?', 'post')
            ->where('table.contents.uid = ?', $user['uid'])
		    ->order('table.contents.cid', 'DESC')
		    ->page($this->_currentPage, $this->parameter->pageSize);
		$this->query($select);

        /** 设置分页 */
        $this->_pageRow = $user;

        /** 设置关键词 */
        $this->_keywords = $user['nickName'];

        /** 设置描述 */
        $this->_description = $user['nickName'];

        /** 设置标题 */
        $this->_title = $user['nickName'];

        /** 设置模板 */
        $this->_themeFile = 'author.php';

        /** 设置类型 */
		$this->_type = 'author';
		
        $this->_alias = $user['uid'];
    }

    /**
     * 处理搜索
     *
     * @return void
     */
    public function searchHandle()
    {
        /** 设置类型 */
        $this->_type = 'search';
		
        $keywords = $this->request->filter('url', 'search')->keywords;

        /** 按post查询 */
        $select = $this->select()
		    ->where('table.contents.type = ?', 'post');
        $searchQuery = '%' . str_replace(' ', '%', $keywords) . '%';
        $select->where('table.contents.title LIKE ? OR table.contents.text LIKE ?', $searchQuery, $searchQuery);
		
		/** 计算数目 */
		$this->_total = (clone $select)
            ->select(array('COUNT(*)' => 'num'))
            ->fetchObject()
			->num;

		$select->page($this->_currentPage, $this->parameter->pageSize);
		
		$this->query($select);

        /** 设置关键词 */
        $this->_keywords = $keywords;

        /** 设置分页 */
        $this->_pageRow = array('keywords' => urlencode($keywords));

        /** 设置标题 */
        $this->_title = $keywords;

        /** 设置模板 */
        $this->_themeFile = 'search.php';

        /** 设置缩略名 */
        $this->_alias = $keywords;
    }

    /**
     * 404页面处理
     *
     * @return void
     */
    private function error404Handle()
    {
        /** 设置header */
        $this->response->status(404);

        /** 设置标题 */
        $this->_title = _t('页面没找到');

        /** 设置类型 */
        $this->_type = 404;

        /** 设置缩略名 */
        $this->_alias = 404;
		
        /** 设置模板 */
        $this->_themeFile = '404.php';

		/** 设置单一类型 */
        $this->_single = false;
    }
	
    public function layout()
    {
		$handles = $this->_layout;
		$type = !empty($this->request->action) ? $this->request->action : 'index';

		if (isset($handles[$type])) {
		    echo $this->widget($handles[$type][0])->{$handles[$type][1]}();
        }
	}	
	
    public function ucenterHandle()
    {
        /** 设置类型 */
		$this->_type = 'ucenter';

        /** 设置模板 */
        $this->_themeFile = 'ucenter.php';
		
        /** 皮肤路径 */
        $this->_themeDir = __COLA_DIR__ . '/var/static/html/';
		
        /** 设置缩略名 */
		$this->_alias = !empty($this->request->action) ? $this->request->action : 'index';

		/** 设置标题 & 初始化Widget_Menu */
		$this->_title = $this->widget('Widget_Menu')->currentTitle;

		if (!$this->_title) {
            throw new Widget_Exception(_t('请求的地址不存在'), 404);
        }
    }

    public function loginHandle()
    {
        /** 设置类型 */
		$this->_type = 'login';
		
        /** 设置模板 */
        $this->_themeFile = 'login.php';
		
        /** 设置标题 */
        $this->_title = _t('登录');
		
		/** 设置参数 */
		$this->request->setParam('action', 'login');
		
        /** 皮肤路径 */
        $this->_themeDir = __COLA_DIR__ . '/var/static/html/';
    }
	
    public function registerHandle()
    {
        /** 设置类型 */
		$this->_type = 'register';

        /** 设置模板 */
        $this->_themeFile = 'register.php';
			
        /** 设置标题 */
        $this->_title = _t('登录');
		
		/** 设置参数 */
		$this->request->setParam('action', 'register');
		
        /** 皮肤路径 */
        $this->_themeDir = __COLA_DIR__ . '/var/static/html/';
    }
	
    public function logoutHandle()
    {
        /** 设置类型 */
		$this->_type = 'logout';

        $this->user->logout();
		
        /** 转向原页 */
        $this->response->redirect($this->options->siteUrl);
    }
	
    /**
     * 重载select
     *
     * @access public
     * @return Db_Query
     */
    public function select()
    {
		/** 插件接口 */
		//HOOK {$plugged} $result | PLUG_Select($this);
		
        if (!$plugged) {
			
			/** 构建基础查询 */
			return parent::select();
        }
		
        return $result;
    }
	
    /**
     * 提交查询
     *
     * @access public
     * @param mixed $select 查询对象
     * @return void
     */
    public function query($select)
    {
		/** 插件接口 */
		//HOOK {$plugged} | PLUG_Query($this, $select);
		
        if (!$plugged) {
            $select->fetchAll(array($this, 'push'));
        }
    }
	
    public function execute()
    {
        /** 避免重复取数据 */
        if ($this->have()) {
            return;
        }

        /** 初始化分页变量 */
        isset($this->request->page) && $this->_currentPage = $this->request->page;

        /** 初始化其它变量 */
        $this->_keywords    = $this->options->keywords;
        $this->_description = $this->options->description;

        /** 处理搜索结果跳转 */
        if (isset($this->request->s)) {
            $filterKeywords = $this->request->filter('search')->s;

            /** 跳转到搜索页 */
            if (NULL != $filterKeywords) {
                $this->response->redirect(Router::url('search',
                    array('keywords' => urlencode($filterKeywords)), $this->options->index));
            }
        }

        if ('ucenter' == $this->parameter->type) {
			
			/** 载入jquery.js */
			/** 载入common.js */
			/** ajax提交表单初始化 */
            $this->widget('Widget_Scripts')
			    ->set($this->options->staticUrl('js/jquery-1.10.2.min.js', false), 'jquery')
                ->set($this->options->staticUrl('js/common.js', false), 'common')
		        ->set('$(document).ready(function () {$(\'.cola-form\').ajaxSubmit();});', 'ajaxSubmit');
				
			/** 载入ucenter.css */
            $this->widget('Widget_Styles')
				->set($this->options->staticUrl('css/ucenter.css', false), 'ucenter');
        }
		
        /** 初始化皮肤函数 */
        $functionsFile = $this->options->themeDir . 'functions.php';
        if ((!$this->_outside || $this->parameter->type == 404)
            && file_exists($functionsFile)) {
            require_once $functionsFile;
            if (function_exists('themeInit')) {
                themeInit($this);
            }
        }

        if (isset($this->_handle[$this->parameter->type])) {
            $handle = $this->_handle[$this->parameter->type];
            $this->{$handle}();
        }
		
        /** 挂接插件 */
		//HOOK PLUG_ThemeInit($this);
    }
	
    /**
     * 输出文章内容
     *
     * @access public
     * @param string $more 文章截取后缀
     * @return void
     */
    public function content($more = NULL)
    {
        parent::content($this->is('single') ? false : $more);
    }

    /**
     * 输出分页
     *
     * @access public
     * @param string $prev 上一页文字
     * @param string $next 下一页文字
     * @param int $splitPage 分割范围
     * @param string $splitWord 分割字符
     * @param string $template 展现配置信息
     * @return void
     */
    public function pageNav($prev = '&laquo;', $next = '&raquo;', $splitPage = 3, $splitWord = '...', $template = '')
    {
        if ($this->have()) {
            $hasNav = false;
            $default = array(
                'wrapTag'       =>  'ol',
                'wrapClass'     =>  'page-navigator'
            );

            if (is_string($template)) {
                parse_str($template, $config);
            } else {
                $config = $template;
            }

            $template = array_merge($default, $config);
            
            $total = $this->_total;
			
			/** 插件接口 */
			//HOOK {$plugged} | PLUG_PageNav($this->_currentPage, $total, $this->parameter->pageSize, $prev, $next, $splitPage, $splitWord);

            if (!$plugged && $total > $this->parameter->pageSize) {
                $query = Router::url($this->parameter->type .
                (false === strpos($this->parameter->type, '_page') ? '_page' : NULL),
                $this->_pageRow, $this->options->index);

                /** 使用盒状分页 */
                $nav = new Page_Box($total, 
                    $this->_currentPage, $this->parameter->pageSize, $query);
                
                echo '<' . $template['wrapTag'] . (empty($template['wrapClass']) 
                    ? '' : ' class="' . $template['wrapClass'] . '"') . '>'.
                 $nav->render($prev, $next, $splitPage, $splitWord, $template) .
                 '</' . $template['wrapTag'] . '>';
            }
        }
    }

    /**
     * 前一页
     *
     * @access public
     * @param string $word 链接标题
     * @param string $page 页面链接
     * @return void
     */
    public function pageLink($word = '&laquo; Previous Entries', $page = 'prev')
    {
        if ($this->have()) {
            if (empty($this->_pageNav)) {
                $query = Router::url($this->parameter->type .
                (false === strpos($this->parameter->type, '_page') ? '_page' : NULL),
                $this->_pageRow, $this->options->index);

                /** 使用盒状分页 */
                $this->_pageNav = new Page_Classic($this->_total,
                $this->_currentPage, $this->parameter->pageSize, $query);
            }

            echo $this->_pageNav->{$page}($word);
        }
    }

    /**
     * 获取评论归档对象
     *
     * @access public
     * @return Widget_Abstract_Comments
     */
    public function comments()
    {
        $parameter = array(
            'parentId'      => $this->cid,
            'parentContent' => $this->row,
            'respondId'     => $this->respondId,
            'commentPage'   => $this->request->filter('int')->commentPage,
            'allowComment'  => $this->allow('comment'),
            'before'        =>  '<ol class="comment-list">',
            'after'         =>  '</ol>',
            'dateFormat'    =>  $this->options->commentDateFormat,
        );

        return $this->widget('Widget_Comments_List', $parameter);
    }

    /**
     * 获取附件对象
     *
     * @access public
     * @param integer $limit 最大个数
     * @param integer $offset 重新
     * @return Widget_Attachs_List
     */
    public function attachments($limit = 0, $offset = 0)
    {
        return $this->widget('Widget_Attachs_List@' . $this->type . '-' . $this->cid . '-' . $limit . '-' . $offset, array(
		    'type'      => $this->type,
		    'id'        => $this->cid,
            'limit'     => $limit,
            'offset'    => $offset
        ));
    }

    /**
     * 显示下一个内容的标题链接
     *
     * @access public
     * @param string $format 格式
     * @param string $default 如果没有下一篇,显示的默认文字
     * @param array $custom 定制化样式
     * @return void
     */
    public function theNext($format = '%s', $default = NULL, $custom = array())
    {
		$row = $this->db->select('table.relate.cid')
		    ->from('table.relate')
			->where('table.relate.cid > ?', $this->cid)
		    ->where('table.relate.mid = ?', $this->mid)
            ->order('table.relate.cid', 'ASC')
            ->limit(1)
			->fetchRow();

        $content = $row ? $this->select()
		    ->where('table.contents.cid = ?', $row['cid'])
            ->limit(1)
			->fetchRow() : '';

        if ($content) {
            $content = $this->filter($content);
            $default = array(
                'title' => NULL,
                'tagClass' => NULL
            );
            $custom = array_merge($default, $custom);
            extract($custom);

            $linkText = empty($title) ? $content['title'] : $title;
            $linkClass = empty($tagClass) ? '' : 'class="' . $tagClass . '" ';
            $link = '<a ' . $linkClass . 'href="' . $content['permalink'] . '" title="' . $content['title'] . '">' . $linkText . '</a>';

            printf($format, $link);
        } else {
            echo $default;
        }
    }

    /**
     * 显示上一个内容的标题链接
     *
     * @access public
     * @param string $format 格式
     * @param string $default 如果没有上一篇,显示的默认文字
     * @param array $custom 定制化样式
     * @return void
     */
    public function thePrev($format = '%s', $default = NULL, $custom = array())
    {
		$row = $this->db->select('table.relate.cid')
		    ->from('table.relate')
			->where('table.relate.cid < ?', $this->cid)
		    ->where('table.relate.mid = ?', $this->mid)
            ->order('table.relate.cid', 'DESC')
            ->limit(1)
			->fetchRow();

        $content = $row ? $this->select()
		    ->where('table.contents.cid = ?', $row['cid'])
            ->limit(1)
			->fetchRow() : '';

        if ($content) {
            $content = $this->filter($content);
            $default = array(
                'title' => NULL,
                'tagClass' => NULL
            );
            $custom = array_merge($default, $custom);
            extract($custom);

            $linkText = empty($title) ? $content['title'] : $title;
            $linkClass = empty($tagClass) ? '' : 'class="' . $tagClass . '" ';
            $link = '<a ' . $linkClass . 'href="' . $content['permalink'] . '" title="' . $content['title'] . '">' . $linkText . '</a>';

            printf($format, $link);
        } else {
            echo $default;
        }
    }

    /**
     * 获取关联内容组件
     *
     * @access public
     * @param integer $limit 输出数量
     * @param string $type 关联类型
     * @return Widget
     */
    public function related($limit = 5, $type = NULL)
    {
        $type = strtolower($type);

        switch ($type) {
            case 'author':
                /** 如果访问权限被设置为禁止,则tag会被置为空 */
                return $this->widget('Widget_Contents_Related_Author',
                array('cid' => $this->cid, 'type' => $this->_type, 'author' => $this->author->uid, 'limit' => $limit));
            default:
                /** 如果访问权限被设置为禁止,则tag会被置为空 */
                return $this->widget('Widget_Contents_Related',
                array('cid' => $this->cid, 'type' => $this->_type, 'tags' => $this->tags, 'limit' => $limit));
        }
    }

    /**
     * 获取文章权限
     *
     * @access public
     */
    public function allow($permission)
    {
        $allow = true;
        if ('edit' == $permission) {
            $allow = ($this->user->pass('editor', true) || $this->uid == $this->user->uid);
        } else {
            /** 对自动关闭反馈功能的支持 */
            if ('comment' == $permission && $this->options->commentsPostTimeout > 0 && $this->options->commentsAutoClose) {
                if ($this->options->time - $this->created > $this->options->commentsPostTimeout) {
                    return false;
                }
            }
            $allow = $this->row['allow' . ucfirst($permission)] == 1;
        }
        return $allow;
    }

    /**
     * 获取主题文件
     *
     * @access public
     * @param string $fileName 主题文件
     * @return void
     */
    public function need($fileName)
    {
        require $this->_themeDir . $fileName;
    }
	
    /**
     * 输出视图
     *
     * @access public
     * @return void
     */
    public function render()
    {

        $validated = false;

        //~ 自定义模板
        if (!empty($this->_themeFile)) {
            if (file_exists($this->_themeDir . $this->_themeFile)) {
                $validated = true;
            }
        }

        if (!$validated && !empty($this->_type)) {

            //~ 首先找具体路径, 比如 category/default.php
            if (!$validated && !empty($this->_alias)) {
                $themeFile = $this->_type . '/' . $this->_alias . '.php';
                if (file_exists($this->_themeDir . $themeFile)) {
                    $this->_themeFile = $themeFile;
                    $validated = true;
                }
            }

            //~ 然后找类型路径, 比如 category.php
            if (!$validated) {
                $themeFile = $this->_type . '.php';
                if (file_exists($this->_themeDir . $themeFile)) {
                    $this->_themeFile = $themeFile;
                    $validated = true;
                }
            }
            //~ 最后找归档路径, 比如 archive.php
            if (!$validated && 'index' != $this->_type) {
                $themeFile = $this->_single ? 'single.php' : 'archive.php';
                if (file_exists($this->_themeDir . $themeFile)) {
                    $this->_themeFile = $themeFile;
                    $validated = true;
                }
            }
			
            if (!$validated) {
                $themeFile = 'index.php';
                if (file_exists($this->_themeDir . $themeFile)) {
                    $this->_themeFile = $themeFile;
                    $validated = true;
                }
            }
        }

        /** 文件不存在 */
        if (!$validated) {
            $this->response->notFound();
        }
            
        /** 挂接插件 */
		//HOOK PLUG_BeforeRender($this);

        /** 输出模板 */
		require_once $this->_themeDir . $this->_themeFile;

        /** 挂接插件 */
		//HOOK PLUG_AfterRender($this);
    }

    /**
     * 输出头部元数据
     *
     * @access public
     * @return void
     */
    public function header($rule = NULL)
    {
        $header = array();

        $allows = array(
            'description'   =>  htmlspecialchars($this->_description),
            'keywords'      =>  htmlspecialchars($this->_keywords),
            'commentReply'  =>  1,
        );

        if (!empty($rule)) {
            parse_str($rule, $rules);
            $allows = array_merge($allows, $rules);
        }
		
		/** 插件接口 */
		//HOOK PLUG_Header_Options($allows, $this);

        if (!empty($allows['description'])) {
            $header[] = '<meta name="description" content="' . $allows['description'] . '" />';
        }

        if (!empty($allows['keywords'])) {
            $header[] = '<meta name="keywords" content="' . $allows['keywords'] . '" />';
        }

        if ($this->options->commentsThreaded && $this->is('single') && $allows['commentReply']) {
            $this->widget('Widget_Scripts')->set("
(function () {
    window.comment = {
        dom : function (id) {
            return document.getElementById(id);
        },
    
        create : function (tag, attr) {
            var el = document.createElement(tag);
        
            for (var key in attr) {
                el.setAttribute(key, attr[key]);
            }
        
            return el;
        },

        reply : function (cid, coid) {
            var comment = this.dom(cid), parent = comment.parentNode,
                response = this.dom('" . $this->respondId . "'), input = this.dom('comment-parent'),
                form = 'form' == response.tagName ? response : response.getElementsByTagName('form')[0],
                textarea = response.getElementsByTagName('textarea')[0];

            if (null == input) {
                input = this.create('input', {
                    'type' : 'hidden',
                    'name' : 'parent',
                    'id'   : 'comment-parent'
                });

                form.appendChild(input);
            }

            input.setAttribute('value', coid);

            if (null == this.dom('comment-form-place-holder')) {
                var holder = this.create('div', {
                    'id' : 'comment-form-place-holder'
                });

                response.parentNode.insertBefore(holder, response);
            }

            comment.appendChild(response);
            this.dom('cancel-comment-reply-link').style.display = '';

            if (null != textarea && 'text' == textarea.name) {
                textarea.focus();
            }

            return false;
        },

        cancelReply : function () {
            var response = this.dom('{$this->respondId}'),
            holder = this.dom('comment-form-place-holder'), input = this.dom('comment-parent');

            if (null != input) {
                input.parentNode.removeChild(input);
            }

            if (null == holder) {
                return true;
            }

            this.dom('cancel-comment-reply-link').style.display = 'none';
            holder.parentNode.insertBefore(response, holder);
            return false;
        }
    };
})();", 'comment');
}

        /** 插件接口 */
		//HOOK $header[] | PLUG_Header($this);

        $header[] = $this->widget('Widget_Styles')->render();

        /** 输出header */
        echo implode("\n", array_filter($header));
    }

    /**
     * 支持页脚自定义
     *
     * @access public
     * @return void
     */
    public function footer()
    {
        $footer = array();

		/** 插件接口 */
		//HOOK $footer[] | PLUG_Footer($this);
		
        $footer[] = $this->widget('Widget_Scripts')->render();

        /** 输出footer */
        echo implode("\n", array_filter($footer));
    }

}

